import { defineStore } from 'pinia'
import { 
  collectNote, 
  uncollectNote, 
  isCollected, 
  getCollectionCountByNoteId,
  getCollectionsByUserId
} from '@/api/collections'
import { useNoteStore } from './notes'

export const useCollectionStore = defineStore('collections', {
  state: () => ({
    isLoading: false,
    error: null,
    collections: []
  }),
  actions: {
    async collectNote(userId, noteId) {
      this.isLoading = true
      this.error = null
      try {
        await collectNote(userId, noteId)
        return true
      } catch (error) {
        this.error = error.response?.data?.message || '收藏失败'
        console.error('收藏失败:', error)
        return false
      } finally {
        this.isLoading = false
      }
    },

    async uncollectNote(userId, noteId) {
      this.isLoading = true
      this.error = null
      try {
        await uncollectNote(userId, noteId)
        return true
      } catch (error) {
        this.error = error.response?.data?.message || '取消收藏失败'
        console.error('取消收藏失败:', error)
        return false
      } finally {
        this.isLoading = false
      }
    },

    async checkIsCollected(userId, noteId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await isCollected(userId, noteId)
        return Boolean(response.data)
      } catch (error) {
        this.error = error.response?.data?.message || '查询收藏状态失败'
        console.error('查询收藏状态失败:', error)
        return false
      } finally {
        this.isLoading = false
      }
    },

    async fetchCollectionCountByNoteId(noteId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getCollectionCountByNoteId(noteId)
        return Number(response.data) || 0
      } catch (error) {
        this.error = error.response?.data?.message || '查询收藏数失败'
        console.error('查询收藏数失败:', error)
        return 0
      } finally {
        this.isLoading = false
      }
    },

    async fetchCollectionsByUserId(userId) {
      this.isLoading = true
      this.error = null
      this.collections = []
      const noteStore = useNoteStore()

      try {
        const collectionResponse = await getCollectionsByUserId(userId)
        const collectionList = collectionResponse.data || []
        if (!collectionList.length) {
          this.collections = []
          return []
        }

        const noteIds = [...new Set(collectionList.map(item => item.noteId))]
        if (!noteIds.length) {
          this.collections = []
          return []
        }

        const notePromises = noteIds.map(noteId => 
          noteStore.fetchNoteById(noteId).catch(err => {
            console.error(`通过 noteId:${noteId} 获取笔记失败:`, err)
            return null 
          })
        )
        const noteResponses = await Promise.all(notePromises)
      
        const validNotes = noteResponses
          .filter(note => note !== null && note.id)
          .map(note => ({
            ...note,
            isCollected: true
          }))

        this.collections = validNotes
        return this.collections

      } catch (error) {
        this.error = error.response?.data?.message || '加载收藏笔记失败'
        console.error('加载收藏笔记失败:', error)
        this.collections = []
        return []
      } finally {
        this.isLoading = false
      }
    },

    removeNoteFromCollection(noteId) {
      this.collections = this.collections.filter(note => note.id !== noteId)
    }
  }
})